import { getFetch } from '@/utils/doFetch';
import { difftime } from '@/utils/time';
import { useModel } from '@umijs/max';
import { useRequest } from 'ahooks';
import { Avatar, List, Select, DatePicker, Input, theme, Tooltip, Skeleton, Divider, Tag } from 'antd';
import dayjs from 'dayjs';
import { useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import { RedoOutlined, SearchOutlined } from '@ant-design/icons';
// import required modules


function Users() {
  const {
    initialState: { fetchProject },
    setInitialState,
  } = useModel('@@initialState');
  const [records, setRecords] = useState([]);
  const [pages, setPages] = useState({
    pageIndex: 1,
    pageSize: 10,
    total: 0,
    orgId: null,
    search: "",
  });

  const { loading, run, refresh } = useRequest(
    async () => {
      let res = await getFetch({ url: '/admin/user', params: { ...pages } });
      return res?.data?.page;
    },
    {
      debounceWait: 600,
      refreshDeps: [pages.pageIndex],
      onSuccess: (res) => {
        setRecords(s => ([...s, ...res?.records]))
        setPages((s) => ({
          ...s,
          total: res?.total ?? 0,
        }));
      },
    },
  );

  const { data } = useRequest(
    async () => {
      let res = await getFetch({ url: '/admin/org/selection', params: {} });
      return res?.data?.dataList ?? [];
    },
    {
      debounceWait: 600,
    },
  );

  const { token } = theme.useToken();
  const { colorBgSecondary, colorOppsites } = token;

  const loadMoreData = () => {
    if (loading) {
      return;
    }
    setPages(s => ({
      ...s,
      pageIndex: s.pageIndex + 1,
    }));
  };

  const {
    orgId,
    search,
  } = pages;



  return (
    <div style={{ flexShrink: 0, marginTop: 24 }}>
      <div className="actionsticky" style={{ backgroundColor: colorOppsites }}>

        <div className="centerr" style={{ gap: 10 }}>
          <Tooltip title="刷新">
            <div
              className="sorts"
              onClick={() => {
                setRecords([]);
                setPages(s => ({
                  ...s,
                  pageIndex: 1,
                }));
                if (pages.pageIndex === 1) {
                  refresh();
                }
              }}
            >
              <RedoOutlined />
            </div>
          </Tooltip>

          <Input
            allowClear
            placeholder='姓名/账号/手机号模糊搜索'
            value={search}
            prefix={<SearchOutlined />}
            style={{ width: 240 }}
            onChange={(e) => {
              let value = e.target.value;
              setRecords([]);
              setPages(s => ({
                ...s,
                search: value,
                pageIndex: 1,
              }));
              if (pages.pageIndex === 1) {
                run();
              }
            }}
          ></Input>

          <Select
            placeholder='请选择组织'
            style={{ width: 140 }}
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            options={data ?? []}
            value={orgId}
            onChange={(value) => {
              setRecords([]);
              setPages(s => ({
                ...s,
                orgId: value,
                pageIndex: 1,
              }));
              if (pages.pageIndex === 1) {
                run();
              }
            }}
            allowClear
          ></Select>
          {/* <DatePicker.RangePicker
            style={{ width: 200 }}
            value={timeRange ? [dayjs(timeRange[0]), dayjs(timeRange[1])] : undefined}
            onChange={(value) => {
              setRecords([]);
              setPages(s => ({
                ...s,
                timeRange: value ? [dayjs(value[0]).format("YYYY-MM-DD"), dayjs(value[1]).format("YYYY-MM-DD")] : null,
                pageIndex: 1,
              }));
              if (pages.pageIndex === 1) {
                run();
              }
            }}
          ></DatePicker.RangePicker> */}
        </div>
        <b style={{ fontSize: 12 }}>
          共
          {' '}
          {pages.total}
          {' '}
          条
        </b>
      </div>
      <div
        id="scrollableDiv"
        style={{
          height: 'calc(100vh - 170px)',
          scrollbarGutter: 'stable',
          marginRight: -12,
          paddingRight: 6
        }}
        className='elements'
      >
        <InfiniteScroll
          dataLength={records.length}
          next={loadMoreData}
          hasMore={records.length < pages.total}
          loader={
            <Skeleton
              avatar
              paragraph={{
                rows: 1,
              }}
              active
            />
          }
          endMessage={<Divider plain>已加载全部</Divider>}
          scrollableTarget="scrollableDiv"
        >
          <List
            loading={loading}
            itemLayout="horizontal"
            dataSource={records}
            renderItem={(item) => {
              return (
                <List.Item
                  style={{
                    padding: '12px',
                    backgroundColor: colorBgSecondary,
                    borderRadius: 12,
                    marginBottom: 16,
                  }}
                  onClick={async () => {
                    await setInitialState((s) => ({
                      ...s,
                      drawerAll: {
                        ...s.drawerAll,
                        item: {
                          id: item.itemId,
                        },
                        open: true,
                      },
                      curitem: item,
                    }));
                  }}
                >
                  <List.Item.Meta
                    avatar={
                      <Tooltip title={item?.createUserName}>
                        <Avatar src={item?.headUrl} size='large'>
                          {item?.headUrl || item?.name.charAt(0)}
                        </Avatar>
                      </Tooltip>
                    }
                    title={<div className="spread gap6" style={{width:"100%"}}>
                      <b>
                        {item?.name}
                      </b>
                      <div className="centerr">
                      <Tag color={item.isBindWx ? '#4c8045' : "#333"}>微信</Tag>
                      <Tag color={item.isBindUtools ? '#F75446' : "#333"} style={{margin:0}}>utools</Tag>
                      </div>
                    </div>}
                    description={
                      <div className="spread" style={{marginTop:6}}>
                        <div className="centerl gap6">
                          <span key={'sad'} style={{ fontSize: 12 }}>
                            {item?.userName}
                          </span>
                        </div>

                        <span key={'sad'} style={{ fontSize: 12 }}>
                          {difftime(dayjs(), dayjs(item.createTime))}
                        </span>
                      </div>

                    }
                  />
                </List.Item>
              );
            }}
          />
        </InfiniteScroll>
      </div>

    </div>
  );
}

export default Users;
